package com.zch.socket.smartsocket.client;

import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;

import java.nio.ByteBuffer;

public class IntegerProtocol implements Protocol<Integer> {
    private static final int INT_LENGTH = 4;
    /**
     *
     * @param readBuffer 待处理的读buffer
     * @param session    本次需要解码的session
     * @param eof        是否EOF
     * @return
     */
    @Override
    public Integer decode(ByteBuffer readBuffer, AioSession<Integer> session, boolean eof) {
        if (readBuffer.remaining() < INT_LENGTH)
            return null;
        return readBuffer.getInt();
    }

    /**
     *
     * @param msg     待编码的业务消息
     * @param session 当前执行encode的AIOSession对象
     * @return
     */
    @Override
    public ByteBuffer encode(Integer msg, AioSession<Integer> session) {
        //设定字节码缓冲区的大小
        ByteBuffer b = ByteBuffer.allocate(INT_LENGTH);
        b.putInt(msg);
        b.flip();
        return b;
    }
}
